<template>
  <div class="add-form file-form">
    <div class="nb-tittle">{{ title }}</div>
    <el-form ref="form" :model="data" label-width="100px" class="hx-form" hide-required-asterisk :rules="rules">
      <el-form-item label="名称：" prop="name">
        <el-input v-model="data.name" class="detail-input" />
      </el-form-item>
      <el-form-item label="电话：" prop="phone">
        <el-input v-model="data.phone" class="detail-input" />
      </el-form-item>
      <el-form-item label="地址：" prop="address">
        <el-input v-model="data.address" class="detail-input" />
      </el-form-item>
      <el-form-item label="联络人：" prop="contact">
        <el-input v-model="data.contact" class="detail-input" />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="data.email" class="detail-input" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import API from '@/api/provider/index'
export default {
  inject: ['goUrl', 'isEdit', 'add', 'update', 'setStorage', 'clearStorage', 'getStorage'],
  data() {
    return {
      data: {},
      title: '',
      editId: '',
      rules: {
        name: { required: true, message: '请输入供应商名称', trigger: 'change' },
        phone: { required: true, message: '请输入电话', trigger: 'change' },
        address: { required: true, message: '请输入地址', trigger: 'change' },
        contact: { required: true, message: '请输入联络人', trigger: 'change' },
        email: { required: true, message: '请输入邮箱', trigger: 'change' }
      }
    }
  },
  created() {
    const edit = this.isEdit()
    if (edit) {
      this.title = '供应商详情'
      this.editId = edit
      this.info()
    } else {
      this.title = '新增供应商'
      this.userName = this.name
      if (this.getStorage('provider')) {
        this.data = this.getStorage('provider')
      }
    }
  },
  mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
  methods: {
    info() {
      API.detail(this.editId).then(res => {
        this.data = res.data
      })
    },
    beforeunloadHandler(e) {
      this.clearStorage('provider')
    },
    cancel() {
      if (!this.editId) {
        this.setStorage('provider', this.data)
      }
      this.goUrl('/provider')
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editId) {
            this.update(API, this.data, '更新成功')
          } else {
            this.add(API, this.data, '新增成功')
            this.clearStorage('provider')
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
